package cn.smbms.util;

import java.util.HashMap;
import java.util.Random;
import java.util.Set;

import com.cloopen.rest.sdk.BodyType;
import com.cloopen.rest.sdk.CCPRestSmsSDK;

public class SendSmsUtil {
	// 生产环境请求地址：app.cloopen.com
	private static final String serverIp = "app.cloopen.com";
	// 请求端口
	private static final String serverPort = "8883";
	// 主账号,登陆云通讯网站后,可在控制台首页看到开发者主账号ACCOUNT SID和主账号令牌AUTH TOKEN
	private static final String accountSId = "8a216da8762cb457017684972ee8216d";
	private static final String accountToken = "da764b17a9284e7eb053f56ca156442a";
	// 请使用管理控制台中已创建应用的APPID
	private static final String appId = "8a216da8762cb457017684972fbe2173";
	private static CCPRestSmsSDK sdk = new CCPRestSmsSDK();
	//
	static {
		sdk.init(serverIp, serverPort);
		sdk.setAccount(accountSId, accountToken);
		sdk.setAppId(appId);
		sdk.setBodyType(BodyType.Type_JSON);
	}

	// 随机生成指定位数验证码
	public static StringBuffer randomCode(int number) {
		// 验证码内容集
		final char[] CHARS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
		StringBuffer stringBuffer = new StringBuffer();
		Random r = new Random();
		for (int i = 0; i < number; i++) {
			stringBuffer.append(CHARS[r.nextInt(CHARS.length)]);
		}
		return stringBuffer;
	}

	// 自定义发送方法
	@SuppressWarnings("unchecked")
	public static boolean sendCode(String to, String code) {
		String templateId = "1";// 测试模板ID
		String[] datas = { "+code+", "5"};//您的验证码是{1}，请于{2}分钟内正确输入
		// String subAppend = "1234"; // 可选 扩展码，四位数字 0~9999
		// String reqId = "fadfafas"; // 可选 第三方自定义消息id，最大支持32位英文数字，同账号下同一自然天内不允许重复
		HashMap<String, Object> result = sdk.sendTemplateSMS(to,templateId,datas);
		// HashMap<String, Object> result = sdk.sendTemplateSMS(to, templateId, datas, subAppend, reqId);
		if ("000000".equals(result.get("statusCode"))) {
			// 正常返回输出data包体信息（map）
			HashMap<String, Object> data = (HashMap<String, Object>) result.get("data");
			Set<String> keySet = data.keySet();
			for (String key : keySet) {
				Object object = data.get(key);
				System.out.println(key + " = " + object);
			}
			return true;
		} else {
			// 异常返回输出错误码和错误信息
			System.out.println("错误码=" + result.get("statusCode") + " 错误信息= " + result.get("statusMsg"));
			return false;
		}

	}

	public static void main(String[] args) {
		sendCode("17731147317", randomCode(6).toString());
	}
}
